import React from 'react'
import {
    FormStep,
    FormItem,
    Input,
    FormButtonGroup,
    Select,
    DatePicker,
    SelectTable,
    Editable,
    Space,
    ArrayItems
} from '@formily/antd-v5'
import {createForm, Field, FormPathPattern, GeneralField, onFieldReact, onFieldValueChange} from '@formily/core'
import {FormProvider, FormConsumer, createSchemaField} from '@formily/react'
import {Button} from 'antd'
import {action} from '@formily/reactive'

const SchemaField = createSchemaField({
    components: {
        FormItem,
        FormStep,
        Input,
        Select,
        DatePicker,
        SelectTable,
        Editable,
        Space,
        ArrayItems,
    },
})
const useAsyncDataSource = (
    pattern: FormPathPattern,
    service: (field: Field) => Promise<{ label: string; value: any }[]>
) => {
    onFieldReact(pattern, (field: Field) => {
        field.loading = true
        service(field).then(
            action.bound?.((data) => {
                field.dataSource = data
                field.loading = false
                field.value = null
            })
        )
    })
}

const getLogicStates = (field: GeneralField) => {
    const logicStatesMap = [
        [
            (field) => field.query('select').value() === '1' &&
                field.query('linkage').value() === 1 &&
                field.query('price').value() > 5,
            () => 'showInput'
        ],
        [
            (field) => field.query('select').value() === '3' &&
                field.query('linkage').value() === 2 &&
                field.query('price').value() <= 5,
            () => 'selectTable'
        ],
        [
            (field) => field.query('select').value() === '4' &&
                field.query('linkage').value() === 2 &&
                field.query('price').value() <= 5,
            () => 'datePicker'
        ],
    ];
    const logicFun = logicStatesMap.find((item) => item[0](field));
    return logicFun ? logicFun[1]() : 'other';
}

const form = createForm({
    initialValues : {
        price: 4
    },
    effects() {
        onFieldValueChange('category', (field) => {
            form.setFieldState('detail', (state) => {
                state.display = field.value
                if (field.value === 'none') state.value = ''
            })
        }),
        onFieldReact('bbb', (field) => {
            if (getLogicStates(field) === 'showInput') {
                field.display = 'visible'
            } else {
                field.display = 'none'
            }
        })
        onFieldReact('selectTable', (field) => {
            if (getLogicStates(field) === 'selectTable') {
                field.display = 'visible'
            } else {
                field.display = 'none'
            }
        })
        onFieldReact('date', (field) => {
            if (getLogicStates(field) === 'datePicker') {
                field.display = 'visible'
            } else {
                field.display = 'none'
            }
        })
        onFieldReact('string_array', (field) => {
            if (getLogicStates(field) === 'other') {
                field.display = 'visible'
            } else {
                field.display = 'none'
            }
        })

        useAsyncDataSource('select', async (field) => {
            const linkage = field.query('linkage').get('value')
            if (!linkage) return []
            return new Promise((resolve) => {
                setTimeout(() => {
                    if (linkage === 1) {
                        resolve([
                            {
                                label: '子选项1',
                                value: '1',
                            },
                            {
                                label: '子选项2',
                                value: '2',
                            },
                        ])
                    } else if (linkage === 2) {
                        resolve([
                            {
                                label: '子选项3',
                                value: '3',
                            },
                            {
                                label: '子选项4',
                                value: '4',
                            },
                        ])
                    }
                }, 500)
            })
        })
    },
})

const formStep = FormStep.createFormStep()

export default () => {
    const checkNext = () => {
        console.log(formStep);
        formStep.submit((values => {
            console.log(values)
        }))
        formStep.next()
    }

    return (
        <FormProvider form={form}>
            <SchemaField>
                <SchemaField.Void
                    x-component="FormStep"
                    x-component-props={{formStep}}
                >
                    <SchemaField.Void
                        x-component="FormStep.StepPane"
                        x-component-props={{title: '第一步'}}
                    >
                        <SchemaField.String
                            name="price"
                            title="价格"
                            x-decorator="FormItem"
                            x-component="Input"
                            required
                            x-component-props={{
                                type: 'number'
                            }}
                        />
                        <SchemaField.Number
                            name="linkage"
                            title="联动选择框"
                            x-decorator="FormItem"
                            x-component="Select"
                            required
                            enum={[
                                {label: '选项1', value: 1},
                                {label: '选项2', value: 2},
                            ]}
                            x-component-props={{
                                style: {
                                    width: 120,
                                },
                            }}
                        />
                        <SchemaField.String
                            name="select"
                            title="异步选择框"
                            x-decorator="FormItem"
                            x-component="Select"
                            required
                            x-component-props={{
                                style: {
                                    width: 120,
                                },
                            }}
                        />
                    </SchemaField.Void>
                    <SchemaField.Void
                        x-component="FormStep.StepPane"
                        x-component-props={{title: '第二步'}}
                    >
                        <SchemaField.String
                            name="bbb"
                            x-decorator="FormItem"
                            required
                            x-component="Input"
                        />
                        <SchemaField.Array
                            type="array"
                            name="selectTable"
                            x-decorator="FormItem"
                            x-component="SelectTable"
                            x-component-props={{
                                bordered: false,
                                showSearch: true,
                                optionAsValue: true,
                            }}
                            enum={[
                                {key: '1', name: '标题1', description: '描述1'},
                                {key: '2', name: '标题2', description: '描述2'},
                            ]}
                        >
                            <SchemaField.Object>
                                <SchemaField.Void
                                    name="name"
                                    title="标题"
                                    x-component="SelectTable.Column"
                                />
                                <SchemaField.Void
                                    name="description"
                                    title="描述"
                                    x-component="SelectTable.Column"
                                />
                            </SchemaField.Object>
                        </SchemaField.Array>
                        <SchemaField.String
                            name="date"
                            required
                            title="普通日期"
                            x-decorator="FormItem"
                            x-component="DatePicker"
                        />
                        <SchemaField.Array
                            name="string_array"
                            title="字符串数组"
                            x-decorator="FormItem"
                            x-component="ArrayItems"
                        >
                            <SchemaField.Void x-component="Space">
                                <SchemaField.Void
                                    x-decorator="FormItem"
                                    x-component="ArrayItems.SortHandle"
                                />
                                <SchemaField.String
                                    x-decorator="FormItem"
                                    required
                                    name="input"
                                    x-component="Input"
                                />
                                <SchemaField.Void
                                    x-decorator="FormItem"
                                    x-component="ArrayItems.Remove"
                                />
                                <SchemaField.Void
                                    x-decorator="FormItem"
                                    x-component="ArrayItems.Copy"
                                />
                            </SchemaField.Void>
                            <SchemaField.Void
                                x-component="ArrayItems.Addition"
                                title="添加条目"
                            />
                        </SchemaField.Array>
                    </SchemaField.Void>
                    <SchemaField.Void
                        type="void"
                        x-component="FormStep.StepPane"
                        x-component-props={{title: '第三步'}}
                    >
                        <code>
                            <pre>
                              <FormConsumer>
                                {(form) => JSON.stringify(form.values, null, 2)}
                              </FormConsumer>
                            </pre>
                        </code>
                    </SchemaField.Void>
                </SchemaField.Void>
            </SchemaField>
            <FormConsumer>
                {() => (
                    <FormButtonGroup>
                        <Button
                            disabled={!formStep.allowBack}
                            onClick={() => {
                                formStep.back()
                            }}
                        >
                            上一步
                        </Button>
                        <Button
                            disabled={!formStep.allowNext}
                            onClick={() => {
                                checkNext()
                            }}
                        >
                            下一步
                        </Button>
                        <Button
                            disabled={formStep.allowNext}
                            onClick={() => {
                                formStep.submit(console.log)
                            }}
                        >
                            提交
                        </Button>
                    </FormButtonGroup>
                )}
            </FormConsumer>
        </FormProvider>
    )
}